package com.qili.util;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.BookmarksNavigator;
import com.spire.doc.documents.TextBodyPart;
import com.spire.doc.fields.TextRange;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Objects.isNull;

/**
 * @Author Zhangshuo
 * @date 2020/11/5 10:20
 **/
public class WordUtil {
    /**
     * 读取文档中表格
     *
     * @param filePath 文档路径
     * @param orderNum 设置需要读取的第几个表格
     */
    public static List<List<String>> getWordTableData(String filePath, Integer orderNum, int pRowidx) throws Exception {
        List<List<String>> tableList = new ArrayList<>();
//        try {
        FileInputStream in = new FileInputStream(filePath);//载入文档
        // 处理docx格式 即office2007以后版本
        if (filePath.toLowerCase().endsWith("docx")) {
            //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
            tableList = getTableData2007Up(in, orderNum, pRowidx);

        } else {
            // 处理doc格式 即office2003版本
            POIFSFileSystem pfs = null;
            try {
                pfs = new POIFSFileSystem(in);

                HWPFDocument hwpf = new HWPFDocument(pfs);
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator itpre = new TableIterator(range);
                ;//得到word中的表格
                int total = 0;
                while (itpre.hasNext()) {
                    itpre.next();
                    total += 1;
                }
                TableIterator it = new TableIterator(range);
                // 迭代文档中的表格
                // 如果有多个表格只读取需要的一个 set是设置需要读取的第几个表格，total是文件中表格的总数
                int set = orderNum;
                int num = set;
                for (int i = 0; i < set - 1; i++) {
                    it.hasNext();
                    it.next();
                }
                while (it.hasNext()) {
                    Table tb = (Table) it.next();
                    System.out.println("这是第" + num + "个表的数据");
                    //迭代行，默认从0开始,可以依据需要设置i的值,改变起始行数，也可设置读取到那行，只需修改循环的判断条件即可

                    for (int i = pRowidx; i < tb.numRows(); i++) {
                        List<String> rowList = new ArrayList<>();
                        TableRow tr = tb.getRow(i);
                        //迭代列，默认从0开始
                        int AiCnt = tr.numCells();
                        int AiNum = 0;
                        for (int j = 0; j < AiCnt; j++) {
                            TableCell td = tr.getCell(j);//取得单元格
                            StringBuilder AsbCellText = new StringBuilder();
                            //取得单元格的内容
                            for (int k = 0; k < td.numParagraphs(); k++) {
                                Paragraph para = td.getParagraph(k);
                                String s = para.text();
                                //去除后面的特殊符号
                                if (null != s && !"".equals(s)) {
                                    s = s.substring(0, s.length() - 1);
                                    AsbCellText.append(s);
                                }
                            }
                            String AsCellText = AsbCellText.toString();
                            if (StringUtil.isBlank(AsCellText)) {
                                AiNum = AiNum + 1;
                            }
                            rowList.add(AsCellText);
                        }
                        if (AiNum == AiCnt) {
                            break;
                        }
                        tableList.add(rowList);
                    }
                    // 过滤多余的表格
                    while (num < total) {
                        it.hasNext();
                        it.next();
                        num += 1;
                    }
                }
                return tableList;
            } catch (OfficeXmlFileException e) {
                // 有个别的文档 后缀 虽然是 doc 但是有时候 会出现 解析异常 ，所有再按照 2007个方法 解析 一遍
                FileInputStream innew = new FileInputStream(filePath);
                tableList = getTableData2007Up(innew, orderNum, pRowidx);
                e.printStackTrace();
            }


        }

        return tableList;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
    }

    public static List<List<String>> getWordTableDataApp(String filePath, Integer orderNum, int pRowidx) throws Exception {
        List<List<String>> tableList = new ArrayList<>();
//        try {
        FileInputStream in = new FileInputStream(filePath);//载入文档
        // 处理docx格式 即office2007以后版本
        if (filePath.toLowerCase().endsWith("docx")) {
            //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
            tableList = getTableData2007UpApp(in, orderNum, pRowidx);

        } else {
            // 处理doc格式 即office2003版本
            POIFSFileSystem pfs = null;
            try {
                pfs = new POIFSFileSystem(in);

                HWPFDocument hwpf = new HWPFDocument(pfs);
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator itpre = new TableIterator(range);
                ;//得到word中的表格
                int total = 0;
                while (itpre.hasNext()) {
                    itpre.next();
                    total += 1;
                }
                TableIterator it = new TableIterator(range);
                // 迭代文档中的表格
                // 如果有多个表格只读取需要的一个 set是设置需要读取的第几个表格，total是文件中表格的总数
                int set = orderNum;
                int num = set;
                for (int i = 0; i < set - 1; i++) {
                    it.hasNext();
                    it.next();
                }
                while (it.hasNext()) {
                    Table tb = (Table) it.next();
                    System.out.println("这是第" + num + "个表的数据");
                    //迭代行，默认从0开始,可以依据需要设置i的值,改变起始行数，也可设置读取到那行，只需修改循环的判断条件即可

                    for (int i = pRowidx; i < tb.numRows(); i++) {
                        List<String> rowList = new ArrayList<>();
                        TableRow tr = tb.getRow(i);
                        //迭代列，默认从0开始
                        int AiCnt = tr.numCells();
                        int AiNum = 0;
                        for (int j = 0; j < AiCnt; j++) {
                            TableCell td = tr.getCell(j);//取得单元格
                            StringBuilder AsbCellText = new StringBuilder();
                            //取得单元格的内容
                            for (int k = 0; k < td.numParagraphs(); k++) {
                                Paragraph para = td.getParagraph(k);
                                String s = para.text();
                                //去除后面的特殊符号
                                if (null != s && !"".equals(s)) {
                                    s = s.substring(0, s.length() - 1);
                                    AsbCellText.append(s);
                                }
                            }
                            String AsCellText = AsbCellText.toString();
                            if (StringUtil.isBlank(AsCellText)) {
                                AiNum = AiNum + 1;
                            }
                            rowList.add(AsCellText);
                        }
                        if (AiNum == AiCnt) {
                            break;
                        }
                        tableList.add(rowList);
                    }
                    // 过滤多余的表格
                    while (num < total) {
                        it.hasNext();
                        it.next();
                        num += 1;
                    }
                }
                return tableList;
            } catch (OfficeXmlFileException e) {
                // 有个别的文档 后缀 虽然是 doc 但是有时候 会出现 解析异常 ，所有再按照 2007个方法 解析 一遍
                FileInputStream innew = new FileInputStream(filePath);
                tableList = getTableData2007UpApp(innew, orderNum, pRowidx);
                e.printStackTrace();
            }


        }

        return tableList;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
    }


    // 处理 2007 版 word
    public static List<List<String>> getTableData2007Up(FileInputStream in, Integer orderNum, int pRowidx) {
        List<List<String>> tableList = new ArrayList<>();
        try {
            XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
            Iterator<XWPFTable> itpre = xwpf.getTablesIterator();//得到word中的表格
            int total = 0;
            while (itpre.hasNext()) {
                itpre.next();
                total += 1;
            }
            Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
            // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
            int set = orderNum;
            int num = set;
            // 过滤前面不需要的表格
            for (int i = 0; i < set - 1; i++) {
                it.hasNext();
                it.next();
            }
            while (it.hasNext()) {
                XWPFTable table = it.next();
                List<XWPFTableRow> rows = table.getRows();
                //读取每一行数据
                for (int i = pRowidx; i < rows.size(); i++) {
                    XWPFTableRow row = rows.get(i);
                    //读取每一列数据
                    List<XWPFTableCell> cells = row.getTableCells();
                    List<String> rowList = new ArrayList<>();
                    int AiCnt = cells.size();
                    int AiNum = 0;
                    if (cells.size() == 10) {

                        System.out.println("你啊那就馬坡地塊的【 ===================================");

                    }
                    for (int j = 0; j < AiCnt; j++) {
                        XWPFTableCell cell = cells.get(j);
                        String AsCellText = cell.getText();
                        if (cells.size() == 10) {
                            //合同对比报告 插入后是 8个单元格 （有一个合并单元格处理）
                            if (j != 3) {
                                if (StringUtil.isBlank(AsCellText)) {
                                    AiNum = AiNum + 1;
                                }
                                rowList.add(AsCellText.replaceAll("\r|\n", "").replace("\"", ""));
                            }
                        } else {
                            if (StringUtil.isBlank(AsCellText)) {
                                AiNum = AiNum + 1;
                            }

                            AsCellText.trim();
                            rowList.add(AsCellText.replaceAll("\r|\n", "").replace("\"", ""));
                        }

                    }
                    if (AiNum == AiCnt) {
                        break;
                    }
                    tableList.add(rowList);
                }
                // 过滤多余的表格
                while (num < total) {
                    it.hasNext();
                    it.next();
                    num += 1;
                }
            }
            xwpf.close();
            in.close();
            return tableList;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return tableList;

    }

    public static List<List<String>> getTableData2007UpApp(FileInputStream in, Integer orderNum, int pRowidx) {
        List<List<String>> tableList = new ArrayList<>();
        try {
            XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
            Iterator<XWPFTable> itpre = xwpf.getTablesIterator();//得到word中的表格
            int total = 0;
            while (itpre.hasNext()) {
                itpre.next();
                total += 1;
            }
            Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
            // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
            int set = orderNum;
            int num = set;
            // 过滤前面不需要的表格
            for (int i = 0; i < set - 1; i++) {
                it.hasNext();
                it.next();
            }
            while (it.hasNext()) {
                XWPFTable table = it.next();
                List<XWPFTableRow> rows = table.getRows();
                //读取每一行数据
                for (int i = pRowidx; i < rows.size(); i++) {
                    XWPFTableRow row = rows.get(i);
                    //读取每一列数据
                    List<XWPFTableCell> cells = row.getTableCells();
                    List<String> rowList = new ArrayList<>();
                    int AiCnt = cells.size();
                    int AiNum = 0;
                    if (cells.size() == 10) {

                        System.out.println("你啊那就馬坡地塊的【 ===================================");

                    }
                    for (int j = 0; j < AiCnt; j++) {
                        XWPFTableCell cell = cells.get(j);
                        String AsCellText = cell.getText();
                        if (StringUtil.isBlank(AsCellText)) {
                            AiNum = AiNum + 1;
                        }

                        AsCellText.trim();
                        rowList.add(AsCellText.replaceAll("\r|\n", "").replace("\"", ""));


                    }
                    if (AiNum == AiCnt) {
                        break;
                    }
                    tableList.add(rowList);
                }
                // 过滤多余的表格
                while (num < total) {
                    it.hasNext();
                    it.next();
                    num += 1;
                }
            }
            xwpf.close();
            in.close();
            return tableList;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return tableList;

    }


    /**
     * @param filePath
     * @param plstTableData
     * @Author:Zhangshuo
     * @Description:合同比对
     * @Date:20:43 2020-12-10
     */
    public static boolean compareContract(String filePath, List<List<String>> plstTableData) throws Exception {
        //载入文档 合同路径
        FileInputStream in = new FileInputStream(filePath);
        try {
            int AiOrder = 1;
            int AiRowIdx = 6;
            // 处理docx格式 即office2007以后版本
            if (filePath.toLowerCase().endsWith("docx")) {
                doDocxWord(filePath, plstTableData, in, AiOrder, AiRowIdx);
                return true;
            } else {
                //doDocWord(plstTableData, in, AiOrder, AiRowIdx);
                throw new Exception("非常抱歉，目前数据解析仅支持Word2007以上版本文件，请另存为2007以上版本文件重试一下。");
            }
        } finally {
//            in.close();
        }
    }

    /**
     * @param plstTableData
     * @param in
     * @param aiOrder
     * @param aiRowIdx
     * @Author:Zhangshuo
     * @Description:
     * @Date:11:38 2020-12-11
     */
    private static void doDocWord(List<List<String>> plstTableData, FileInputStream in, int aiOrder, int aiRowIdx) throws IOException {
        //处理doc格式 即office2003版本
        POIFSFileSystem pfs = new POIFSFileSystem(in);
        HWPFDocument hwpf = new HWPFDocument(pfs);
        Range range = hwpf.getRange();
        //得到文档的读取范围
        TableIterator itpre = new TableIterator(range);
        int total = 0;
        while (itpre.hasNext()) {
            itpre.next();
            total += 1;
        }
        TableIterator it = new TableIterator(range);
        // 迭代文档中的表格
        // 如果有多个表格只读取需要的一个 set是设置需要读取的第几个表格，total是文件中表格的总数
        int set = aiOrder;
        int num = set;
        for (int i = 0; i < set - 1; i++) {
            it.hasNext();
            it.next();
        }
        while (it.hasNext()) {
            Table tb = (Table) it.next();
            for (int i = aiRowIdx; i < tb.numRows(); i++) {
                TableRow tr = tb.getRow(i);
                //序号
                TableCell cellNo = tr.getCell(0);
                //区域
                TableCell cellQy = tr.getCell(1);
                String AsQy = getCellText(cellQy);
                //名称
                TableCell cellName = tr.getCell(2);
                String AsName = getCellText(cellName);
                //品牌
                TableCell cellpp = tr.getCell(3);
                String AsBrand = getCellText(cellpp);
                //型号
                TableCell cellxh = tr.getCell(4);
                String AsXH = getCellText(cellxh);
                String AsRealNum = getSameRowByNameBrandXH(plstTableData, AsQy, AsName, AsBrand, AsXH);
                if (StringUtil.isNotBlank(AsRealNum)) {
                    TableCell AcRealCell = tr.getCell(5);
                    setCellText(AcRealCell, AsRealNum);
                } else {
                    //addRowByBottom(plstTableData, tb, i, cells, cellNo, AsName, AsBrand);
                }
            }
            // 过滤多余的表格
            while (num < total) {
                it.hasNext();
                it.next();
                num += 1;
            }
        }
        //写出
        FileOutputStream out = new FileOutputStream("D:\\30.doc");
        try {
            hwpf.write(out);
        } finally {
            out.flush();
            out.close();
            pfs.close();
            in.close();
        }
    }

    /**
     * @param filePath
     * @param plstTableData
     * @param in
     * @param aiOrder
     * @param aiRowIdx
     * @Description: 处理2007以上word
     * @Author:Zhangshuo
     * @Date:15:06 2020-12-15
     */
    private static void doDocxWord(String filePath, List<List<String>> plstTableData, FileInputStream in, int aiOrder, int aiRowIdx) throws IOException {
        //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
        XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
        Iterator<XWPFTable> itpre = xwpf.getTablesIterator();//得到word中的表格
        int total = 0;
        while (itpre.hasNext()) {
            itpre.next();
            total += 1;
        }
        Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
        // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
        int set = aiOrder;
        int num = set;
        // 过滤前面不需要的表格
        for (int i = 0; i < set - 1; i++) {
            it.hasNext();
            it.next();
        }
        while (it.hasNext()) {
            XWPFTable table = it.next();
            List<XWPFTableRow> rows = table.getRows();
            //处理有相同产品，品牌或者型号
            int AiIdx = doSameRecords(plstTableData, aiRowIdx, table, rows);
            //将剩余数据加入表格20210827
            //
            // addListOtherData(plstTableData, table, rows, AiIdx);
        }
        //过滤多余的表格
        while (num < total) {
            it.hasNext();
            it.next();
            num += 1;
        }
        //写出
        try (FileOutputStream out = new FileOutputStream(filePath)) {
            xwpf.write(out);
        }
    }

    /**
     * @param plstTableData
     * @param table
     * @param rows
     * @param AiIdx
     * @Description:
     * @Author:Zhangshuo
     * @Date:15:54 2020-12-15
     */
    private static void addListOtherData(List<List<String>> plstTableData, XWPFTable table, List<XWPFTableRow> rows, int AiIdx) {
        if (plstTableData.size() > 0) {
            for (List<String> Aitem : plstTableData) {
                XWPFTableRow AxrNewRow = null;
                if (AiIdx == rows.size() - 2) {
                    AxrNewRow = table.insertNewTableRow(AiIdx);
                    XWPFTableCell cellNo = AxrNewRow.addNewTableCell();
                    setCellText(cellNo, (AiIdx - 5) + "");
                    //名称
                    XWPFTableCell cellName = AxrNewRow.addNewTableCell();
                    cellName.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    XWPFTableCell AcNewName1 = AxrNewRow.addNewTableCell();
                    AcNewName1.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                    setCellText(cellName, Aitem.get(1));
                    //品牌
                    XWPFTableCell cellpp = AxrNewRow.addNewTableCell();
                    setCellText(cellpp, Aitem.get(2));
                    //型号
                    XWPFTableCell cellxh = AxrNewRow.addNewTableCell();
                    setCellText(cellxh, Aitem.get(3));
                    //数量
                    XWPFTableCell cellSL = AxrNewRow.addNewTableCell();
                    setCellText(cellSL, Aitem.get(4));
                    /*实际数量*/
                    XWPFTableCell cellSLSJ = AxrNewRow.addNewTableCell();
                    setCellText(cellSLSJ, Aitem.get(4));
                    XWPFTableCell cellSL1 = AxrNewRow.addNewTableCell();
                    XWPFTableCell cellSL2 = AxrNewRow.addNewTableCell();
                } else {
                    AxrNewRow = table.getRow(AiIdx);
                    List<XWPFTableCell> cells = AxrNewRow.getTableCells();
                    XWPFTableCell cellNo = cells.get(0);
                    setCellText(cellNo, (AiIdx - 5) + "");
                    //名称
                    XWPFTableCell cellName = cells.get(1);
                    setCellText(cellName, Aitem.get(1));
                    //品牌
                    XWPFTableCell cellpp = cells.get(2);
                    setCellText(cellpp, Aitem.get(2));
                    //型号
                    XWPFTableCell cellxh = cells.get(3);
                    setCellText(cellxh, Aitem.get(3));
                    //数量
                    XWPFTableCell cellSL = cells.get(4);
                    setCellText(cellSL, Aitem.get(4));

                    XWPFTableCell cellSLSj = cells.get(5);
                    setCellText(cellSLSj, Aitem.get(4));


                }
            }
        }
    }

    /**
     * @param plstTableData
     * @param aiRowIdx
     * @param table
     * @param rows
     * @Description: 处理有相同产品，品牌或者型号
     * @Author:Zhangshuo
     * @Date:15:08 2020-12-15
     */
    private static int doSameRecords(List<List<String>> plstTableData, int aiRowIdx, XWPFTable table, List<XWPFTableRow> rows) {
        int AiIdx = -1;
        for (int i = aiRowIdx; i < rows.size() - 2; i++) {
            XWPFTableRow row = rows.get(i);
            //读取每一列数据
            List<XWPFTableCell> cells = row.getTableCells();
            //序号
            XWPFTableCell cellNo = cells.get(0);
            String AsNo = cellNo.getText().trim();
//            if (AsNo.indexOf("*") == -1) {
            //区域
            XWPFTableCell cellQy = cells.get(1);
            String AsQy = cellQy.getText().trim().replaceAll("\r|\n", "").replace("\"", "");
            //名称
            XWPFTableCell cellName = cells.get(2);
            String AsName = cellName.getText().trim().replaceAll("\r|\n", "").replace("\"", "");
            String AsBrand = "";
            String AsXH = "";
            if (cells.size() == 10) {
                //品牌
                XWPFTableCell cellpp = cells.get(4);
                AsBrand = cellpp.getText().trim().replaceAll("\r|\n", "").replace("\"", "");
                //型号
//            XWPFTableCell cellxh = cells.get(4);
//            String AsXH = cellxh.getText().trim().replaceAll("\r|\n", "").replace("\"", "");
                XWPFTableCell cellxh = cells.get(5);
                AsXH = cellxh.getText().trim().replaceAll("\r|\n", "").replace("\"", "");
            } else {
                //品牌
                XWPFTableCell cellpp = cells.get(3);
                AsBrand = cellpp.getText().trim().replaceAll("\r|\n", "").replace("\"", "");
                //型号
                XWPFTableCell cellxh = cells.get(4);
                AsXH = cellxh.getText().trim().replaceAll("\r|\n", "").replace("\"", "");

            }

            if (StringUtil.isBlank(AsName) && StringUtil.isBlank(AsBrand) && StringUtil.isBlank(AsXH)) {
                AiIdx = i;
                break;
            } else {
                //从货物清单中 读取 该品牌 规格 型号
                String AsRealNum = getSameRowByNameBrandXH(plstTableData, AsQy, AsName, AsBrand, AsXH);
                if (StringUtil.isNotBlank(AsRealNum)) {
                    XWPFTableCell AcRealCell = null;
                    if (cells.size() == 10) {
                        AcRealCell = cells.get(8);
                    } else {
                        AcRealCell = cells.get(7);
                    }

                    String textnum = AcRealCell.getText();
                    /*相同品牌 规格 名称 每次 累加数量*/
                    if (StringUtil.isNotBlank(textnum)) {
                        Integer num = Integer.valueOf(textnum) + Integer.valueOf(AsRealNum);
                        setCellText(AcRealCell, num + "");
                    } else {
                        setCellText(AcRealCell, AsRealNum);
                    }

                } else {
                    /*变更处理*/
//                        addRowByBottom(plstTableData, table, i, cells, cellNo, AsName, AsBrand);
                }
            }
//            }
        }
        if (AiIdx == -1) {
            AiIdx = rows.size() - 2;
        }
        return AiIdx;
    }

    /**
     * @param plstTableData
     * @param table
     * @param i
     * @param cells
     * @param cellNo
     * @param asName
     * @param asBrand
     * @Author:Zhangshuo
     * @Description:
     * @Date:23:26 2020-12-10
     */
    private static void addRowByBottom(List<List<String>> plstTableData, XWPFTable table, int i, List<XWPFTableCell> cells, XWPFTableCell cellNo, String asName, String asBrand) {
        List<String> AlstNewRow = getSameRowByNameBrand(plstTableData, asName, asBrand);
        if (!isNull(AlstNewRow)) {
            String AsNo = cellNo.getText();
            setCellText(cellNo, "*" + AsNo);
            XWPFTableRow AxrNewRow = table.insertNewTableRow(i + 1);
            //序号
            XWPFTableCell AcNewcNo = AxrNewRow.addNewTableCell();
            setCellText(AcNewcNo, AsNo + "*");
            //名称
            XWPFTableCell AcNewName = AxrNewRow.addNewTableCell();
            setCellText(AcNewName, AlstNewRow.get(1));
            AcNewName.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            XWPFTableCell AcNewName1 = AxrNewRow.addNewTableCell();
            AcNewName1.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);

            //品牌
            XWPFTableCell AcNewpp = AxrNewRow.addNewTableCell();
            setCellText(AcNewpp, AlstNewRow.get(2));
            //型号
            XWPFTableCell AcNewXh = AxrNewRow.addNewTableCell();
            setCellText(AcNewXh, AlstNewRow.get(3));
            //数量
            XWPFTableCell AsNewNum = AxrNewRow.addNewTableCell();
            setCellText(AsNewNum, AlstNewRow.get(4));
            //数量
            XWPFTableCell AsNewRealNum = AxrNewRow.addNewTableCell();
            setCellText(AsNewRealNum, AlstNewRow.get(7));

            /*变更的实际数量修改为0*/
            XWPFTableCell realCell = cells.get(5);
            setCellText(realCell, "0");
            //备注
            XWPFTableCell AsNewNote = AxrNewRow.addNewTableCell();

            XWPFTableCell AsOldNote = cells.get(6);
            AsOldNote.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            AsNewNote.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            setCellText(AsOldNote, "变更");
        }
    }

    /**
     * @param pTableData
     * @param pName
     * @param pBrand
     * @Author:Zhangshuo
     * @Description:
     * @Date:23:23 2020-12-10
     */
    private static List<String> getSameRowByNameBrand(List<List<String>> pTableData, String pName, String pBrand) {
        int AiCnt = pTableData.size();
        int AiIdx = -1;
        List<String> AlstItem = new ArrayList<>();
        for (int i = 0; i < AiCnt; i++) {
            AlstItem = pTableData.get(i);
            if (pName.equals(AlstItem.get(1)) && pBrand.equals(AlstItem.get(2))) {
                AiIdx = i;
                break;
            }
        }
        if (AiIdx != -1) {
            /*相同删除该行数据*/
            pTableData.remove(AiIdx);
        }
        return AlstItem;
    }

    /**
     * @param pTableData
     * @param pName
     * @param pBrand
     * @param pXh
     * @Description:根据产品名称，品牌和型号获取是否有相同的
     * @Author:Zhangshuo
     * @Date:23:23 2020-12-10
     */
    private static String getSameRowByNameBrandXH(List<List<String>> pTableData, String pQy, String pName, String pBrand, String pXh) {
        int AiCnt = pTableData.size();
        String AsRealNum = "";
        int AiIdx = -1;
        for (int i = 0; i < AiCnt; i++) {
            List<String> AlstItem = pTableData.get(i);
            if (pQy.equals(AlstItem.get(1).trim().replaceAll("\r|\n", "").replace("\"", "")) && pName.equals(AlstItem.get(2).trim().replaceAll("\r|\n", "").replace("\"", "")) && pBrand.equals(AlstItem.get(3).trim().replaceAll("\r|\n", "").replace("\"", "")) && pXh.equals(AlstItem.get(4).trim().replaceAll("\r|\n", "").replace("\"", ""))) {
                AsRealNum = AlstItem.get(9);
                AiIdx = i;
            }
        }
        if (AiIdx != -1) {
            /*相同删除该行数据*/
            pTableData.remove(AiIdx);
        }
        return AsRealNum;
    }

    /**
     * @param pCell
     * @param pCellText
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:04 2020-12-11
     */
    private static void setCellText(XWPFTableCell pCell, String pCellText) {
        List<XWPFParagraph> AlstPara = pCell.getParagraphs();
        if (AlstPara.size() > 0) {
            XWPFParagraph xwpfParagraph = AlstPara.get(0);
            xwpfParagraph.setIndentationFirstLine(1);
            xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
            List<XWPFRun> AlstRuns = xwpfParagraph.getRuns();
            if (AlstRuns.size() > 0) {
                AlstRuns.get(0).setText(pCellText, 0);
            } else {
                xwpfParagraph.createRun().setText(pCellText, 0);
            }
        } else {
            pCell.setText(pCellText);
        }
    }

    /**
     * @param pCell
     * @param pCellText
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:04 2020-12-11
     */
    private static void setCellText(TableCell pCell, String pCellText) {
        pCell.getCharacterRun(0).insertBefore(pCellText);
    }

    /**
     * @param pCell
     * @Author:Zhangshuo
     * @Description:
     * @Date:11:34 2020-12-11
     */
    private static String getCellText(TableCell pCell) {
        StringBuilder AsbCellText = new StringBuilder();
        for (int k = 0; k < pCell.numParagraphs(); k++) {
            Paragraph para = pCell.getParagraph(k);
            String s = para.text();
            //去除后面的特殊符号
            if (null != s && !"".equals(s)) {
                s = s.substring(0, s.length() - 1);
                AsbCellText.append(s);
            }
        }
        return AsbCellText.toString();
    }

    /**
     * @param plstTableData
     * @param filePath
     * @Author:Zhangshuo
     * @Description: 合同对比报告填充货物清单
     * @Date:15:53 2020-12-09
     */
    public static boolean savecompareContractFillList(HashMap map, List<List<String>> plstTableData, String filePath) throws Exception {
        int AiOrder = 1;
        int AiRowIdx = 6;
        //载入合同对比报告文档
        FileInputStream in = new FileInputStream(filePath);
        // 获取合同对比报告原来数据
        List<List<String>> AlstWordDataOld = WordUtil.getWordTableData(filePath, 1, 6);
        Map oldDataMap = new HashMap<String, List<String>>();

        if (AlstWordDataOld != null && AlstWordDataOld.size() > 0) {
            //说明合同对比报告有内容
            for (List<String> aRow : AlstWordDataOld) {
                // 如果是文档中的设备数据，则把名称、品牌、型号、 作为map的key,本条数据作为value
                if (aRow.size() > 6) {
                    // 2021 0815  模板增加了两列  区域和单位
                    String aKey = aRow.get(1) + "-" + aRow.get(2) + "-" + aRow.get(3) + "-" + aRow.get(4);
                    //String aKey = aRow.get(1)+"-"+aRow.get(2)+"-"+aRow.get(3);
                    if (!"--".equals(aKey)) {
                        oldDataMap.put(aKey, aRow);
                    }
                }
            }
        }

        // 处理docx格式 即office2007以后版本
        if (filePath.toLowerCase().endsWith("docx")) {
            //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
            XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
            Iterator<XWPFTable> itpre = xwpf.getTablesIterator();//得到word中的表格
            int total = 0;
            while (itpre.hasNext()) {
                itpre.next();
                total += 1;
            }
            Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
            // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
            int set = AiOrder;
            int num = set;
            // 过滤前面不需要的表格
            for (int i = 0; i < set - 1; i++) {
                it.hasNext();
                it.next();
            }
            List<List<String>> tableList = new ArrayList<>();
            while (it.hasNext()) {
                XWPFTable table = it.next();
                List<XWPFTableRow> rows = table.getRows();
                /*处理前四行数据*/
                for (int i = 0; i < 4; i++) {
                    XWPFTableRow row = rows.get(i);
                    //读取每一列数据
                    List<XWPFTableCell> cells = row.getTableCells();
                    XWPFTableCell cellNo = cells.get(1);
                    if (i == 0) {
                        String projectName = map.get("projectName") + "";
                        if (StringUtil.isNotBlank(projectName)) {
                            setCellText(cellNo, projectName);
                        }
                    } else if (i == 1) {
                        String yzCompany = map.get("yzCompany") + "";
                        if (StringUtil.isNotBlank(yzCompany)) {
                            setCellText(cellNo, yzCompany);
                        }
                    } else if (i == 2) {
                        String jlCompany = map.get("jlCompany") + "";
                        if (StringUtil.isNotBlank(jlCompany)) {
                            setCellText(cellNo, jlCompany);
                        }
                    } else if (i == 3) {
                        String cjCompany = map.get("cjCompany") + "";
                        if (StringUtil.isNotBlank(cjCompany)) {
                            setCellText(cellNo, cjCompany);
                        }
                    }
                }
                int AiJumpCnt = 0;
                List<XWPFTableCell> cellList = null;
                //读取每一行数据---从第6行开始获取 AiRowIdx=6   end  rows.size() - 2 (去除 说明和签章)
                for (int i = AiRowIdx; i < rows.size() - 2; i++) {
                    XWPFTableRow row = rows.get(i);
                    //读取每一列数据
                    List<XWPFTableCell> cells = row.getTableCells();
                    cellList = cells;
                    //序号
//                    XWPFTableCell cellNo = cells.get(0);
//                    String AsNo = cellNo.getText().trim();
//                    //名称
//                    XWPFTableCell cellName = cells.get(1);
//                    String AsName = cellName.getText().trim();
//                    //品牌
//                    XWPFTableCell cellpp = cells.get(2);
//                    String text3 = cellpp.getText();
//                    //型号
//                    XWPFTableCell cellxh = cells.get(3);
//                    String text2 = cellxh.getText();
//                    //数量
//                    XWPFTableCell cellsl = cells.get(4);
//                    String text1 = cellsl.getText();
//                    XWPFTableCell cellxx = cells.get(5);
//                    String text = cellxx.getText();
//
//                    XWPFTableCell cellsjnum = cells.get(6);
//                    String textnum = cellxx.getText();
                    // 20210815 增加两列
                    //序号
                    XWPFTableCell cellNo = cells.get(0);
                    String AsNo = cellNo.getText().trim();
                    // 区域
                    XWPFTableCell qyName = cells.get(1);
                    String qytext = qyName.getText().trim();

                    //名称
                    XWPFTableCell cellName = cells.get(2);
                    String AsName = cellName.getText().trim();
                    //品牌
                    XWPFTableCell cellpp = cells.get(3);
                    String text3 = cellpp.getText();
                    //型号
                    XWPFTableCell cellxh = cells.get(4);
                    String text2 = cellxh.getText();
                    //数量
                    XWPFTableCell cellsl = cells.get(5);
                    String text1 = cellsl.getText();
                    // 单位
                    XWPFTableCell cellsdw = cells.get(6);
                    String textdw = cellsdw.getText();
                    // 实际情况
                    XWPFTableCell cellxx = cells.get(7);
                    String text = cellxx.getText();
                    //和备注
                    XWPFTableCell cellsjnum = cells.get(8);
                    String textnum = cellxx.getText();
//                    if (StringUtil.isNotBlank(AsNo) && StringUtil.isNotBlank(AsName)) {
//                        AiJumpCnt = AiJumpCnt + 1;
//                        continue;
//                    } else {
                    // plstTableData 为获取清单中的数据
                    // 如果货物清单中的数据大于
                    if (plstTableData.size() > (i - AiRowIdx - AiJumpCnt)) {
                        //获取货物清单中的数据
                        List<String> AlstRowData = plstTableData.get(i - AiRowIdx - AiJumpCnt);

                        if (cells.size() == 10) {
                            setCellText(cellNo, AlstRowData.get(0));
                            System.out.println(AlstRowData + "数据====================");
                            String ll = AlstRowData.get(1);
                            System.out.println(ll + "美麗的");
                            setCellText(qyName, ll);
                            setCellText(cellName, AlstRowData.get(2));
                            setCellText(cellxh, AlstRowData.get(3));
                            setCellText(cellsl, AlstRowData.get(4));
                            setCellText(cellsdw, AlstRowData.get(6));
                            setCellText(cellxx, AlstRowData.get(7));// 单位
                            Object oldDataStrListObj = oldDataMap.get(AlstRowData.get(1) + "-" + AlstRowData.get(2) + "-" + AlstRowData.get(3) + "-" + AlstRowData.get(4));
                            if (oldDataStrListObj != null) {
                                List<String> oldDataStrList = (List<String>) oldDataStrListObj;
                                // 原来合同 数据的实际情况
                                setCellText(cellsjnum, oldDataStrList.get(7));
                            } else {
                                setCellText(cellsjnum, "");
                            }
                        } else {
                            System.out.println("=========开始=================");
                            if (StringUtils.isNotBlank(AlstRowData.get(0))) {
                                String s = AlstRowData.get(0);
                                if (s.indexOf("填表说明") > -1) {
                                    System.out.println("填表说明-过滤---");
                                    continue;
                                }
                            }
                            setCellText(cellNo, AlstRowData.get(0));
                            System.out.println("=========开始cellNo0=================" + cellNo);
                            System.out.println("=========开始cellNo0=================" + AlstRowData);
                            setCellText(qyName, AlstRowData.get(1));
                            System.out.println("=========开始qyName1=================" + qyName);
                            System.out.println("=========开始qyName1=================" + AlstRowData);


                            setCellText(cellName, AlstRowData.get(2));
                            System.out.println("=========结束=================");
                            CTTcPr ctTcPr = cellName.getCTTc().addNewTcPr();
                            CTTblWidth ctTblWidth = ctTcPr.addNewTcW();
                            BigInteger w = ctTblWidth.getW();
                            System.out.println(w + "宽度====================================");
                            setCellText(cellpp, AlstRowData.get(3));
                            setCellText(cellxh, AlstRowData.get(4));
                            setCellText(cellsl, AlstRowData.get(6));
                            setCellText(cellsdw, AlstRowData.get(7));// 单位
                            Object oldDataStrListObj = oldDataMap.get(AlstRowData.get(1) + "-" + AlstRowData.get(2) + "-" + AlstRowData.get(3) + "-" + AlstRowData.get(4));
                            if (oldDataStrListObj != null) {
                                // 原来合同 数据的实际情况
                                List<String> oldDataStrList = (List<String>) oldDataStrListObj;
                                setCellText(cellxx, oldDataStrList.get(7));
                            } else {
                                setCellText(cellxx, "");
                            }
                        }

                    } else {
                        //删除行:
                        setCellText(cellNo, "");
                        setCellText(qyName, "");
                        setCellText(cellName, "");
                        setCellText(cellpp, "");
                        setCellText(cellxh, "");
                        setCellText(cellsl, "");
                        setCellText(cellxx, "");
                        setCellText(cellsdw, "");
                    }
//                    }
                }

                if (plstTableData.size() > rows.size() - 8) {
                    //原始数据行数多:
                    //给表格添加行:
                    for (int i = rows.size() - 2; i < plstTableData.size() + 6; i++) {
                        List<String> strings = plstTableData.get(i - 6);
                        if (strings.size() > 6) {
                            XWPFTableRow AxrNewRow = table.insertNewTableRow(i);
                            //序号
                            XWPFTableCell AcNewcNo = AxrNewRow.addNewTableCell();
                            setCellText(AcNewcNo, strings.get(0));
                            AcNewcNo.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            //区域
                            XWPFTableCell AcNewcQy = AxrNewRow.addNewTableCell();
                            setCellText(AcNewcQy, strings.get(1));
                            AcNewcQy.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            //名称
                            XWPFTableCell AcNewName = AxrNewRow.addNewTableCell();
                            CTTcPr ctTcPr = AcNewName.getCTTc().addNewTcPr();

                            ctTcPr.addNewHMerge().setVal(STMerge.RESTART);
//                            CTTblWidth ctTblWidth = ctTcPr.addNewTcW();
//                            ctTblWidth.setW(BigInteger.valueOf(1));
                            XWPFTableCell AcNewName1 = AxrNewRow.addNewTableCell();
                            CTTcPr ctTcPr1 = AcNewName1.getCTTc().addNewTcPr();
                            AcNewName.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            AcNewName1.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            AcNewName1.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                            setCellText(AcNewName, strings.get(2));

                            //品牌
                            XWPFTableCell AcNewpp = AxrNewRow.addNewTableCell();
                            setCellText(AcNewpp, strings.get(3));
                            AcNewpp.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            //型号
                            XWPFTableCell AcNewXh = AxrNewRow.addNewTableCell();
                            setCellText(AcNewXh, strings.get(4));
                            AcNewXh.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            //数量
                            XWPFTableCell AsNewNum = AxrNewRow.addNewTableCell();
                            setCellText(AsNewNum, strings.get(6));
                            AsNewNum.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            // 单位
                            XWPFTableCell AsNewDw = AxrNewRow.addNewTableCell();
                            setCellText(AsNewDw, strings.get(7));
                            AsNewDw.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            //实际情况
                            XWPFTableCell AsNewRealNum = AxrNewRow.addNewTableCell();
                            setCellText(AsNewRealNum, "");
                            AsNewRealNum.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                            //备注
                            XWPFTableCell AsRemark = AxrNewRow.addNewTableCell();
                            setCellText(AsRemark, "");
                            AsRemark.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1440));
                        }
                    }
                }

                //过滤多余的表格
                while (num < total) {
                    it.hasNext();
                    it.next();
                    num += 1;
                }
            }
            //写出
            try (FileOutputStream out = new FileOutputStream(filePath)) {
                xwpf.write(out);
            }
            return true;
        } else {
            throw new Exception("目前只支持2007版以上的Word文件（后缀名为.docx）");
        }

    }

    /**
     * @param map
     * @param mapdata
     * @param filePath
     * @Author:zhaoyongke
     * @Description: 处理变更统计表
     * @Date:11:13 2021/1/13
     */
    public static boolean saveBgtjList(HashMap map, HashMap mapdata, String filePath) throws Exception {
        int AiOrder = 1;
        int AiRowIdx = 5;
        //载入文档
        FileInputStream in = new FileInputStream(filePath);
        // 处理docx格式 即office2007以后版本
        if (filePath.toLowerCase().endsWith("docx")) {
            XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
            //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
            Iterator<XWPFTable> itpre = xwpf.getTablesIterator();//得到word中的表格
            int total = 0;
            while (itpre.hasNext()) {
                itpre.next();
                total += 1;
            }
            Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
            // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
            int set = AiOrder;
            int num = set;
            // 过滤前面不需要的表格
            for (int i = 0; i < set - 1; i++) {
                it.hasNext();
                it.next();
            }
            List<List<String>> tableList = new ArrayList<>();
            while (it.hasNext()) {
                XWPFTable table = it.next();
                List<XWPFTableRow> rows = table.getRows();
                /*处理前四行数据*/
                for (int i = 0; i < 4; i++) {
                    XWPFTableRow row = rows.get(i);
                    //读取每一列数据
                    List<XWPFTableCell> cells = row.getTableCells();
                    XWPFTableCell cellNo = cells.get(1);
                    if (i == 0) {
                        String projectName = map.get("projectName") + "";
                        if (StringUtil.isNotBlank(projectName) && !"null".equals(projectName)) {
                            setCellText(cellNo, projectName);
                        }
                    } else if (i == 1) {
                        String yzCompany = map.get("yzCompany") + "";
                        if (StringUtil.isNotBlank(yzCompany) && !"null".equals(yzCompany)) {
                            setCellText(cellNo, yzCompany);
                        }
                    } else if (i == 2) {
                        String jlCompany = map.get("jlCompany") + "";
                        if (StringUtil.isNotBlank(jlCompany) && !"null".equals(jlCompany)) {
                            setCellText(cellNo, jlCompany);
                        }
                    } else if (i == 3) {
                        String cjCompany = map.get("cjCompany") + "";
                        String text = cellNo.getText();
                        if (StringUtil.isNotBlank(cjCompany) && !"null".equals(cjCompany)) {
                            if (StringUtil.isNotBlank(text)) {
                                if (text.indexOf(cjCompany) == -1) {
                                    setCellText(cellNo, text + "," + cjCompany);
                                }
                            } else {
                                setCellText(cellNo, cjCompany);
                            }

                        }
                    }
                }
                /*已经存在的数据行数*/
                int AiJumpCnt = 0;
                //读取每一行数据
                for (int i = AiRowIdx; i < rows.size() - 1; i++) {
                    XWPFTableRow row = rows.get(i);
                    //读取每一列数据
                    List<XWPFTableCell> cells = row.getTableCells();
                    //序号
                    XWPFTableCell cellNo = cells.get(0);
                    String AsNo = cellNo.getText().trim();
                    //产品名称
                    XWPFTableCell cellName = cells.get(1);
                    String AsName = cellName.getText().trim();
                    //变更前
                    XWPFTableCell cellbefore = cells.get(2);
                    //变更后
                    XWPFTableCell cellafter = cells.get(3);
                    //变更原因
                    XWPFTableCell cellreson = cells.get(4);
                    //变更金额
                    XWPFTableCell cellJe = cells.get(5);
                    //变更单号
                    XWPFTableCell cellDh = cells.get(6);
                    if (StringUtil.isNotBlank(AsNo) && StringUtil.isNotBlank(AsName)) {
                        AiJumpCnt = AiJumpCnt + 1;
                        continue;
                    } else {
                        setCellText(cellNo, (i - AiRowIdx + 1) + "");
                        //产品名称
                        setCellText(cellName, mapdata.get("name") + "");
                        //变更前
                        setCellText(cellbefore, mapdata.get("before") + "");
                        //变更后
                        setCellText(cellafter, mapdata.get("after") + "");
                        /*原因*/
                        setCellText(cellreson, mapdata.get("reason") + "");
                        /*变更金额*/
                        setCellText(cellJe, mapdata.get("money") + "");
                        setCellText(cellDh, mapdata.get("dh") + "");
                        break;
                    }
                }
                /*文档中有的行数*/
                int tablerowlength = rows.size() - 6;
                if (AiJumpCnt == tablerowlength) {
                    /*文档中表格已满，追加一行*/
                    XWPFTableRow AxrNewRow = table.insertNewTableRow(AiJumpCnt + 5);
                    //序号
                    XWPFTableCell AcNewcNo = AxrNewRow.addNewTableCell();
                    int indexno = AiJumpCnt + 1;
                    /*序号*/
                    setCellText(AcNewcNo, indexno + "");
                    //名称
                    XWPFTableCell AcNewName = AxrNewRow.addNewTableCell();
                    setCellText(AcNewName, mapdata.get("name") + "");
                    AcNewName.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    XWPFTableCell AcNewName1 = AxrNewRow.addNewTableCell();
                    AcNewName1.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                    //变更前
                    XWPFTableCell AcBefore = AxrNewRow.addNewTableCell();
                    setCellText(AcBefore, mapdata.get("before") + "");
          /*          CTTc cttc = AcBefore.getCTTc();
                    CTTcPr ctPr = cttc.addNewTcPr();
                    ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                    cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);*/
                    //变更后
                    XWPFTableCell AcAfter = AxrNewRow.addNewTableCell();
                    setCellText(AcAfter, mapdata.get("after") + "");
                    //原因
                    XWPFTableCell Acreason = AxrNewRow.addNewTableCell();
                    setCellText(Acreason, mapdata.get("reason") + "");
                    /*变更金额*/
                    XWPFTableCell Acmoney = AxrNewRow.addNewTableCell();
                    setCellText(Acmoney, mapdata.get("money") + "");
                    /*变更单号*/
                    XWPFTableCell dh = AxrNewRow.addNewTableCell();
                    setCellText(dh, mapdata.get("dh") + "");
                }
            }
            //过滤多余的表格
            while (num < total) {
                it.hasNext();
                it.next();
                num += 1;
            }
            try (FileOutputStream out = new FileOutputStream(filePath)) {
                xwpf.write(out);
            }
        } else {
            throw new Exception("目前只支持2007版以上的Word文件（后缀名为.docx）");
        }
        return true;
    }

    /**
     * @param targetWordPath
     * @Author:zhaoyongke
     * @Description: 保存文档为docx 格式 防止 插入的文档 错乱
     * @Date:10:51 2021/1/7
     */
    public static void saveWordDocx(String targetWordPath) throws Exception {
        try {
            //targetWordPath文档
            Document targetword = new Document(targetWordPath);
            targetword.saveToFile(targetWordPath, FileFormat.Docx_2010);
            InputStream is = new FileInputStream(targetWordPath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetWordPath);
            document.write(os);
            System.out.println("生成docx文档成功！");
        } catch (Exception e) {
            throw new Exception("合并文档出错：" + e.getMessage());
        }
    }

    /**
     * @param targetWordPath
     * @param copyWordPath
     * @Author:zhaoyongke
     * @Description: 合并文档
     * @Date:10:51 2021/1/7
     */
    public static void mergeWord(String targetWordPath, String copyWordPath) throws Exception {
        try {
            //targetWordPath文档
            //targetWordPath文档
            Document targetword = new Document(targetWordPath);
            //copyWordPath插入到targetWordPath文档
            targetword.insertTextFromFile(copyWordPath, FileFormat.Docx_2010);
            //保存合并后的文档
            targetword.saveToFile(targetWordPath, FileFormat.Docx_2010);
            InputStream is = new FileInputStream(targetWordPath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetWordPath);
            document.write(os);
            System.out.println("生成docx文档成功！");
        } catch (Exception e) {
            throw new Exception("合并文档出错：" + e.getMessage());
        }
    }

    /**
     * @param url
     * @param list
     * @Author:zhaoyongke
     * @Description:通过书签获取文字
     * @Date:13:33 2021/1/13
     */
    public static HashMap getTextByLebel(String url, List<String> list) throws Exception {
        HashMap map = new HashMap();
        Document doc = new Document();
        //加载Word文档
        doc.loadFromFile(url);
        for (int i = 0; i < list.size(); i++) {
            //获取指定书签
            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            /*获取书签*/
            String lebel = list.get(i);
            navigator.moveToBookmark(lebel);
            //获取书签内容
            TextBodyPart textBodyPart = navigator.getBookmarkContent();
            //创建String变量
            String text = "";
            //遍历书签内容的项目
            for (Object item : textBodyPart.getBodyItems()) {
                //判断项目是否为段落
                if (item instanceof com.spire.doc.documents.Paragraph) {
                    com.spire.doc.documents.Paragraph paragraph = (com.spire.doc.documents.Paragraph) item;
                    //遍历段落中的子对象
                    for (Object childObj : paragraph.getChildObjects()) {
                        //判断子对象是否为TextRange
                        if (childObj instanceof TextRange) {
                            //获取TextRange中的文本
                            TextRange textRange = (TextRange) childObj;
                            text = text + textRange.getText();
                        }
                    }
                }
            }
            //将获取到的文本写入Txt文件
            System.out.println(text);
            if ("PO_F1".equals(lebel)) {
                String textnew = text.replaceAll("由于", "").replaceAll("原因", "").replaceAll("_", "");
                if (StringUtil.isBlank(textnew)) {
                    throw new Exception("解析文档出错：获取变更原因失败！请填写变更原因");
                }
                map.put("reason", textnew);
            } else if ("PO_F2".equals(lebel)) {
                String textnew = text.replaceAll("兹提出", "").replaceAll("产品名称", "").replaceAll("_", "");
                if (StringUtil.isBlank(textnew)) {
                    throw new Exception("解析文档出错：获取产品名称失败！请填写产品名称");
                }
                map.put("name", textnew);
            } else if ("PO_F3".equals(lebel)) {
                String textnew = text.replaceAll("由", "").replaceAll("变更", "").replaceAll("_", "");
                if (StringUtil.isBlank(textnew)) {
                    throw new Exception("解析文档出错：获取变更内容失败！请填写变更内容");
                }
                map.put("before", textnew);
            } else if ("PO_F4".equals(lebel)) {
                String textnew = text.replaceAll("为", "").replaceAll("的工程变更", "").replaceAll("_", "");
                if (StringUtil.isBlank(textnew)) {
                    throw new Exception("解析文档出错：获取变更内容失败！请填写变更内容");
                }
                map.put("after", textnew);
            } else if ("PO_F5".equals(lebel)) {
                String textnew = text.replaceAll("变更金额为", "").replaceAll("（内容见附件）", "").replaceAll("_", "");
                if (StringUtil.isBlank(textnew)) {
                    throw new Exception("解析文档出错：获取金额失败！请填写金额");
                }
                map.put("money", textnew);
            } else if ("PO_F6".equals(lebel)) {
                String textnew = text.replaceAll("文档编号：", "");
                if (StringUtil.isBlank(textnew)) {
                    throw new Exception("解析文档出错：提取文档编号失败");
                }
                map.put("dh", textnew);
            }
        }


        return map;
    }

    /**
     * @param sourceFile
     * @param targetFile
     * @Author:zhaoyongke
     * @Description: 签章
     * @Date:15:33 2021/1/10addStampImage
     */
    public static void addStampImageTableClearQz(String sourceFile, String targetFile, String imageGzurl, String imageQzurl, String contenttext, Boolean gz, Boolean qz) throws Exception {
        Document doc1 = new Document();
        doc1.loadFromFile(sourceFile);
        doc1.saveToFile(sourceFile, FileFormat.Docx_2013);
        XWPFDocument doc;
        Boolean isFind = false;
        try {
            doc = new XWPFDocument(new FileInputStream(sourceFile));
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {//遍历每一个单元格
                        if (cell.getText().contains(contenttext)) {//如果遇到"&章"则进行替换
                            try {
                                System.out.println(cell.getText() + "kkkkkkkkkkkk");
                                isFind = true;
                                insertCellStampClear(cell, imageGzurl, imageQzurl, gz, qz);//给带有要盖章字样的单元格 加上章的图片
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

            FileOutputStream fos = new FileOutputStream(targetFile);
            doc.write(fos);
            fos.close();
            doc.write(new FileOutputStream(targetFile));
            InputStream is = new FileInputStream(targetFile);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetFile);
            document.write(os);
            os.close();
            doc1.close();
         /*   if(!isFind){
                throw new Exception("没有发现关键字 ");
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());

        }
    }

    /**
     * @param sourceFile
     * @param targetFile
     * @Author:zhaoyongke
     * @Description: 签章
     * @Date:15:33 2021/1/10addStampImage
     */
    public static void addStampImageTable(String sourceFile, String targetFile, String imageGzurl, String imageQzurl, String keyword, String contenttext, Boolean gz, Boolean qz, int leftsetGz, int leftsetQz, String filetype) throws Exception {
        Document doc1 = new Document();
        doc1.loadFromFile(sourceFile);
        doc1.saveToFile(sourceFile, FileFormat.Docx_2013);
        XWPFDocument doc;
        Boolean isFind = false;
        try {
            doc = new XWPFDocument(new FileInputStream(sourceFile));
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {//遍历每一个单元格
                        if (cell.getText().contains(contenttext)) {//如果遇到"&章"则进行替换
                            System.out.println(cell.getText() + "kkkkkkkkkkkk");
                            isFind = true;
                            insertCellStamp(cell, imageGzurl, imageQzurl, keyword, gz, qz, leftsetGz, leftsetQz, filetype);//给带有要盖章字样的单元格 加上章的图片
                        }
                    }
                }
            }

            FileOutputStream fos = new FileOutputStream(targetFile);
            doc.write(fos);
            fos.close();
            doc.write(new FileOutputStream(targetFile));
            InputStream is = new FileInputStream(targetFile);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetFile);
            document.write(os);
            os.close();
            doc1.close();
         /*   if(!isFind){
                throw new Exception("没有发现关键字 ");
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());

        }
    }


    /**
     * <b> Word中添加图章
     * </b><br><br><i>Description</i> :
     * String srcPath, 源Word路径
     * String storePath, 添加图章后的路径
     * String sealPath, 图章路径（即图片）
     * tString abText, 在Word中盖图章的标识字符串，如：(签字/盖章)
     * int width, 图章宽度
     * int height, 图章高度
     * int leftOffset, 图章在编辑段落向左偏移量
     * int topOffset, 图章在编辑段落向上偏移量
     * boolean behind，图章是否在文字下面
     */

    /**
     * @param sourceFile
     * @param targetFile
     * @param imageurl
     * @param keyword
     * @Author:zhaoyongke
     * @Description: 针对文件搜索（非表格 中关键字搜索替换图片） 盖章形式
     * @Date:14:46 2021/1/27
     */
    public static void addStampBykeyWord(String sourceFile, String targetFile, String imageurl, String keyword, int left, int top) throws Exception {
        Document doc1 = new Document();
        doc1.loadFromFile(sourceFile);
        doc1.saveToFile(sourceFile, FileFormat.Docx_2013);
        InputStream is = null;
        try {
            XWPFDocument doc;
            doc = new XWPFDocument(new FileInputStream(sourceFile));
            List<XWPFParagraph> paragraphs = doc.getParagraphs();
            XWPFRun targetRun = null;
            XWPFParagraph paragraph1 = null;
            Boolean isfind = false;
            for (XWPFParagraph paragraph : paragraphs) {
                if (!"".equals(paragraph.getText()) && paragraph.getText().contains(keyword)) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    paragraph1 = paragraph;
                    targetRun = runs.get(runs.size() - 1);
                    isfind = true;
                    break;
                }
            }
            if (isfind) {
                if (targetRun != null) {
                    System.out.println("签章操作开始---------------------");
                    InputStream in = new FileInputStream(imageurl);//设置图片路径
                    //创建Random类对象
                    Random random = new Random();
                    //产生随机数
                    int number = random.nextInt(999) + 1;
                    targetRun = paragraph1.createRun();
                    targetRun.addPicture(in, XWPFDocument.PICTURE_TYPE_JPEG, "Seal" + number, Units.toEMU(60), Units.toEMU(60));
                    in.close();
                    // 2. 获取到图片数据
                    CTDrawing drawing = targetRun.getCTR().getDrawingArray(0);
                    CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
                    //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
                    CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Seal" + number,
                            Units.toEMU(150), Units.toEMU(150),//图片大小
                            Units.toEMU(left), Units.toEMU(top), false);//相对当前段落位置 需要计算段落已有内容的左偏移
                    drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性
                    drawing.removeInline(0);//删除行内属性
                    System.out.println("签章操作结束---------------------");
                }
            }

            FileOutputStream fos = new FileOutputStream(targetFile);
            doc.write(fos);
            fos.close();
            doc.write(new FileOutputStream(targetFile));
            is = new FileInputStream(targetFile);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetFile);
            document.write(os);
            os.close();
            is.close();
            doc1.close();
            if (!isfind) {
                throw new Exception("没有发现关键字 " + keyword);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("操作失败：" + e.getMessage());

        }
    }


    private static void insertCellStampClear(XWPFTableCell cell, String imageGzurl, String imageQzurl, Boolean gz, Boolean qz) throws Exception {

        //清空单元格里的内容
        for (XWPFParagraph para : cell.getParagraphs()) {
            //插入图片
            for (int i = 0; i < para.getRuns().size(); i++) {
                XWPFRun run = para.getRuns().get(i);
                run.setText("", 0);
            }
        }
        for (XWPFParagraph para : cell.getParagraphs()) {
            //插入图片
            for (int i = 0; i < para.getRuns().size(); i++) {
                if (i == 0) {
                    try {
                        XWPFRun run = para.getRuns().get(i);
                        String text = run.text();
                        System.out.println(text + "ppppppppppppppppp");
                        Random random = new Random();
                        int number = random.nextInt(999) + 1;
                        //添加签名图片
                        System.out.println("签名开始------------------------");
                        run = para.createRun();
                        FileInputStream is2 = new FileInputStream(imageQzurl);
                        run.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imageQzurl, Units.toEMU(120), Units.toEMU(60));
                        is2.close();
                        random = new Random();
                        CTDrawing drawing2 = run.getCTR().getDrawingArray(0);
                        CTGraphicalObject graphicalobject2 = drawing2.getInlineArray(0).getGraphic();
                        number = random.nextInt(999) + 1;
                        /*只是签名*/
                        CTAnchor anchor2 = getAnchorWithGraphic(graphicalobject2, "Seal" + number,
                                Units.toEMU(120), Units.toEMU(40),//图片大小
                                Units.toEMU(0), Units.toEMU(0), false);
                        drawing2.setAnchorArray(new CTAnchor[]{anchor2});//添加浮动属性
                        drawing2.removeInline(0);//删除行内属性
                        System.out.println("签名结束------------------------");
                    } catch (Exception e) {
                        System.out.println("Error: ========  插入公章图片时出错了:可能是图片路径不存在");
                        e.printStackTrace();
                        throw new Exception("Error: ========  插入公章图片时出错了:可能是图片路径不存在");

                    }
                    break;
                }

            }
        }
    }


    /**
     * @param cell
     * @Author:zhaoyongke
     * @Description: 单元格文字 查询图片
     * @Date:15:40 2021/1/14
     */
    private static void insertCellStamp(XWPFTableCell cell, String imageGzurl, String imageQzurl, String keyword, Boolean gz, Boolean qz, int leftsetGz, int leftsetQz, String filetype) throws Exception {

        Boolean isfind = false;
        for (XWPFParagraph para : cell.getParagraphs()) {
            for (int i = 0; i < para.getRuns().size(); i++) {
                XWPFRun run = para.getRuns().get(i);
                String text = run.text();
                //  System.out.println(text + "ppppppppppppppppp");
                if (text.contains("&")) {
                    isfind = true;
                    break;
                }
            }

        }

        Boolean isqz = false;
        // 盖章
        Boolean isgzhangoper = false;
        // 签字
        Boolean issignoper = false;
        for (XWPFParagraph para : cell.getParagraphs()) {
            int k = 0;
            Boolean isfindyear = false;

            //插入图片
            for (int i = 0; i < para.getRuns().size(); i++) {

                XWPFRun run = para.getRuns().get(i);
                String text = run.text();
                String containtext = "";
                if ("&章".equals(keyword)) {
                    containtext = "章";
                } else if ("&签字".equals(keyword)) {
                    containtext = "签字";
                }
                if ((text.contains(containtext)) && isfind) {
                    /*删除盖章关键字*/
                    if ("签字".equals(containtext)) {
                        isqz = true;
                        if (text.indexOf("&") < 0) {
                            XWPFRun runbefore = para.getRuns().get(i - 1);
                            String textbefore = runbefore.text();
                            if (StringUtil.isNotBlank(textbefore)) {
                                textbefore.replace("&", "");
                                runbefore.setText(textbefore.replace("&", ""), 0);
                            }
                        }
                        run.setText(text.replace("签字", "").replace("&", ""), 0);
                    } else if ("章".equals(containtext)) {
                        if (text.indexOf("&") < 0) {
                            XWPFRun runbefore = para.getRuns().get(i - 1);
                            String textbefore = runbefore.text();
                            if (StringUtil.isNotBlank(textbefore)) {
                                textbefore.replace("&", "");
                                runbefore.setText(textbefore.replace("&", ""), 0);
                            }
                        }
                        String kk = text.replace("章", "").replace("&", "");
                        run.setText(kk, 0);
                    }

                    Random random = new Random();
                    int number = random.nextInt(999) + 1;
                    // 20210812 修改 先 签字后盖章
                    if (qz) {

                        issignoper = true;
                        //添加签名图片
                        System.out.println("签名开始------------------------");
                        FileInputStream is1 = new FileInputStream(imageQzurl);
                        run.addPicture(is1, XWPFDocument.PICTURE_TYPE_JPEG, imageGzurl, Units.toEMU(120), Units.toEMU(60));
                        is1.close();
                        CTDrawing drawing1 = run.getCTR().getDrawingArray(0);
                        CTGraphicalObject graphicalobject1 = drawing1.getInlineArray(0).getGraphic();
                        //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
                        CTAnchor anchor1 = getAnchorWithGraphic(graphicalobject1, "Seal" + number,
                                Units.toEMU(120), Units.toEMU(60),//图片大小
                                Units.toEMU(leftsetQz), Units.toEMU(0), true);//相对当前段落位置及偏移
                        drawing1.setAnchorArray(new CTAnchor[]{anchor1});//添加浮动属性
                        drawing1.removeInline(0);//删除行内属性
                        System.out.println("签字結束------------------------");
                    }
                    if (gz) {
                        isgzhangoper = true;
                        //添加签名图片
                        System.out.println("盖章开始------------------------");
                        run = para.createRun();
                        FileInputStream is2 = new FileInputStream(imageGzurl);
                        run.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imageQzurl, Units.toEMU(60), Units.toEMU(60));
                        is2.close();
                        random = new Random();
                        CTDrawing drawing2 = run.getCTR().getDrawingArray(0);
                        CTGraphicalObject graphicalobject2 = drawing2.getInlineArray(0).getGraphic();
                        number = random.nextInt(999) + 1;
                        CTAnchor anchor2 = null;
                        if (!qz) {
                            /*只是盖章*/
                            anchor2 = getAnchorWithGraphic(graphicalobject2, "Seal" + number,
                                    Units.toEMU(120), Units.toEMU(120),//图片大小 负值 代表向上
                                    Units.toEMU(leftsetGz), Units.toEMU(-20), false);//  相对当前段落位置及偏移
                        } else {
                            /*盖章+签字*/
                            anchor2 = getAnchorWithGraphic(graphicalobject2, "Seal" + number,
                                    Units.toEMU(120), Units.toEMU(120),//图片大小 负值 代表向上
                                    Units.toEMU(leftsetGz), Units.toEMU(-20), false);
                        }
                        drawing2.setAnchorArray(new CTAnchor[]{anchor2});//添加浮动属性
                        drawing2.removeInline(0);//删除行内属性
                        System.out.println("盖章结束------------------------");
                    }


                }

                if (StringUtil.isNotBlank(filetype)) {
                    if (!"036".equals(filetype) && !"037".equals(filetype) && !"106".equals(filetype)) {
                        if (text.indexOf("年") != -1 && !isfindyear) {
                            /**/
                            String strDate = DateUtil.formatDate(new Date(), "yyyy年MM月dd日");
                            run.setText(strDate, 0);
                            isfindyear = true;
                            k = i;
                        }
                        if (isfindyear && i > k) {
                            /*将多余的年月日 替换成空*/
                            if (text.indexOf("年") != -1 || text.indexOf("月") != -1 || text.indexOf("日") != -1) {
                                run.setText("", 0);
                            }
                        }

                    }

                } else {
                    if (text.indexOf("年") != -1 && !isfindyear && (isgzhangoper || issignoper)) {
                        /**/
                        String strDate = DateUtil.formatDate(new Date(), "yyyy年MM月dd日");
                        run.setText(text.replace("年", "").replace("月", "").replace("日", "") + strDate, 0);
                        isfindyear = true;
                        k = i;
                    }
                    if (isfindyear && i > k) {
                        /*将多余的年月日 替换成空*/
                        if (text.indexOf("年") != -1 || text.indexOf("月") != -1 || text.indexOf("日") != -1) {
                            run.setText("", 0);
                        }
                    }
                }


            }

        }

        if ("036".equals(filetype) || "037".equals(filetype) || "106".equals(filetype)) {
            Boolean riqi = false;
            for (XWPFParagraph para : cell.getParagraphs()) {
                for (int i = 0; i < para.getRuns().size(); i++) {
                    XWPFRun run = para.getRuns().get(i);
                    String text = run.text();
                    Boolean riqicreate = true;
                    if (text.contains("日期") && isqz) {
                        if (i + 1 < para.getRuns().size()) {
                            XWPFRun runnext = para.getRuns().get(i + 1);
                            if (StringUtil.isNotBlank(runnext.text())) {
                                int index_v = runnext.text().indexOf("20");
                                if (index_v > -1) {
                                    /*如果下行有时间则不生成日期*/
                                    riqicreate = false;
                                }

                            }
                            ;

                        }
                        if (riqicreate) {
                            String strDate = DateUtil.formatDate(new Date(), "yyyy年MM月dd日");
                            System.out.println(text + "KKKKKKKKK");
                            String newtext = text.substring(0, text.indexOf("日期"));
                            run.setText(newtext + "日期：" + strDate, 0);
                            riqi = true;
                            break;
                        }


                    }
                }
                if (riqi) {
                    break;
                }

            }


        }
        if (!"088".equals(filetype) && !"089".equals(filetype) && !"109".equals(filetype) && !"091".equals(filetype) && !"110".equals(filetype)) {
            /*支付意见   监理通知*/
            for (XWPFParagraph para : cell.getParagraphs()) {
                for (int i = 0; i < para.getRuns().size(); i++) {
                    XWPFRun run = para.getRuns().get(i);
                    String text = run.text();
                    if (text.contains("&")) {
                        run.setText(text.replace("&", ""), 0);

                    }
                }

            }
        }


    }

    /**
     * @param ctGraphicalObject
     * @param deskFileName
     * @param width
     * @param height
     * @param leftOffset,       图章在编辑段落向左偏移量
     * @param topOffset,        图章在编辑段落向上偏移量
     * @param behind，图章是否在文字下面
     * @Author:zhaoyongke
     * @Description:
     * @Date:18:22 2021/1/26
     */
    public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
                                                String deskFileName, int width, int height,
                                                int leftOffset, int topOffset, boolean behind) {
        String anchorXML =
                "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\">"
                        + "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
                        + "</wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\">"
                        + "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
                        "</wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapNone/>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";

        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);
        } catch (XmlException e) {
            e.printStackTrace();
        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }

    public static void replaceBookmark(String filePath, String docUrl, Map<String, String> bookmarkMap) {
        //加载包含书签的文档
        Document doc = new Document();
        InputStream is = null;
        OutputStream os = null;
        try {
            doc.loadFromFile(docUrl);
            Iterator iter = bookmarkMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String bookmark = entry.getKey().toString();
                if (entry.getValue() != null) {
                    String value = entry.getValue().toString();
                    //定位到指定书签位置
                    BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc);
                    bookmarksNavigator.moveToBookmark(bookmark);
                    bookmarksNavigator.replaceBookmarkContent(value, true);
                }
            }
            //保存doc文档
            doc.saveToFile(filePath, FileFormat.Docx_2013);
            is = new FileInputStream(filePath);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            os = new FileOutputStream(filePath);
            document.write(os);
            is.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("替换书签报错：" + e.getMessage());
        } finally {
            doc.dispose();
        }
    }


}
